$(function() {

	$('#pageSize').change(function() {
		var item = $("#pageSize option:selected").text();
		dataPage(1);
	});
	var dataPage = function(cpage) {
		var item = $("#pageSize option:selected").text();
		var data = {
			item: item,
			index: cpage
		};
		$.ajax({
			url: '/api/resource?',
			type: 'GET',
			data : {'item':item, 'index':cpage, '_t':new Date().getTime()},
			success: function(data) {
				var page;
				// $("#showCount").html("共"+ data.count + "条记录");
				if (data.count < item) {
					page = 1;
				} else {
					page = Math.ceil(data.count / item);
				}

				var options = {
					currentPage: cpage,
					totalPages: page,
					alignment: 'right',
					count:data.count,
					selectorId: 'pageSeletct',
					onPageChanged: function(e, oldPage, newPage) {
						dataPage(newPage);
					}
				};

				$('#paginator').bootstrapPaginator(options);
				$("#pageSeletct").change(function() {
					var page = $("#pageSeletct option:selected").val();
					$('#paginator').bootstrapPaginator("show",page);
				});
				initialize(data.data, cpage);

			},
			error: function(result) {
				alert('error');
			}

		});
	};
	dataPage(1);



	var initialize = function(rdata, cpage) {
		$("#urlMessage").css("display", "none");
		$("#nameMessage").css("display", "none");

		$('#resourceBody').html('');

		var template = "<tr><td class=center><span id=resName>{{name}}</span><input type=hidden id='id' value={{id}}></td><td class=center><span id=url>{{url}}</span></td><td class=center><i id=editIcon style='cursor:pointer;' class='icon-pencil bigger-150'></i>&nbsp;&nbsp;&nbsp;<i id='deleteIcon' style='cursor:pointer;' class='icon-trash  bigger-150'></i></td></tr>";
		if (rdata == "") {
			$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>没有相关信息</div>");
			return;
		} else {
			$('#tip').html("");
		}
		//获取资源名
		$.each(rdata, function(i, resource) {
			var data = {
				name: resource.resName,
				url: resource.resUrl,
				id: resource.id
			};

			var $html = $(Mustache.to_html(template, data));

			$('#resourceBody').append($html);

			//定义删除资源操作
			$html.find('#deleteIcon').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				deleteRes($html);
			});

			//定义编辑资源操作
			$html.find('#editIcon').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				var name = $html.find('#resName').html();
				var url = $html.find('#url').html();
				var id = $html.find('#id').val();

				var editData = {
					resName: name,
					resUrl: url,
					id: id
				};
				addResource(editData,cpage);
			});
		});

	}

	//新增加资源
	$('#resourcebtn').click(function() {
		addResource(null, 0);
	});

	//取消按钮
	$('#cancleBtn').click(function() {
		$('#resourceAdd').modal('hide');
		$("#urlMessage").css("display", "none");
		$("#nameMessage").css("display", "none");
	});
	//添加或更新资源
	var addResource = function(resourceData, cpage) {
		var pageSize = $("#pageSize option:selected").text();
		var count = parseInt($("#showCount").html());
		$('#resourceAdd').modal('show');

		if (resourceData != null) {
			$("#myModalLabel1").html("编辑资源");
			$('#resourcename').val(resourceData.resName);
			$('#resourceurl').val(resourceData.resUrl);
			$('#resourceId').val(resourceData.id);
		} else {
			$("#myModalLabel1").html("添加资源");
			$('#resourcename').val('');
			$('#resourceurl').val('');
			$('#resourceId').val('');
		}


		$('#resourceAddSave').unbind('click');
		$('#resourceAddSave').bind('click', function() {
			var resource = $('#resourcename').val();
			var url = $('#resourceurl').val();
			var id = $('#resourceId').val();
			if (resource == null || resource == '' || resource == undefined) {
				$("#urlMessage").css("display", "none");
				$("#nameMessage").css("display", "block");
				$("#nameMsg").html("请填写资源名");
				return;
			}
			if (url == null || url == '' || url == undefined) {
				$("#nameMessage").css("display", "none");
				$("#urlMessage").css("display", "block");
				$("#urlMsg").html("请输入url");
				return;
			}
			var checkName = false;
			var checkUrl = false;

			$.get('/api/resource', function(data, status) {
				// console.info('data:', data);
				// console.info('status:', status);
				if (status == 'success') {
					$.each(data, function(i, item) {
						// console.info('item', item);
						if (resource == item.resName && id != item.id) {
							checkName = true;
						}
						if (url == item.resUrl && id != item.id) {
							checkUrl = true;
						}
					});

					if (checkName == true) {
						$("#urlMessage").css("display", "none");
						$("#nameMessage").css("display", "block");
						$("#nameMsg").html("资源名重复");
						return;
					}
					if (checkUrl == true) {
						// bootbox.alert("url已存在，请重新输入!");
						$("#nameMessage").css("display", "none");
						$("#urlMessage").css("display", "block");
						$("#urlMsg").html("url已存在");
						return;
					}

					//var ajaxurl = resourceData != null ? '/api/resource/' + resourceData.id : '/api/resource';
					var type = resourceData != null ? 'PUT' : 'POST';
					var data = resourceData != null ? {
						id: resourceData.id,
						resName: resource,
						resUrl: url
					} : {
						resName: resource,
						resUrl: url
					};

					$.ajax({
						url: '/api/resource',
						type: type,
						data: data,
						success: function(result) {
							if(result == 'noPrivilege'){
								bootbox.alert('您没有权限,操作失败！');
								return;
							}
							if(type == "PUT") {
								bootbox.alert("更新资源成功！");
								// dataPage(cpage);
							}else if(type == "POST") {
								bootbox.alert("添加资源成功！");
								cpage = Math.ceil(count / pageSize);
								if((count % pageSize) == 0) {
									cpage = cpage + 1;
								}
							}
							$('#resourceAdd').modal('hide');
							dataPage(cpage);
						},
						error: function(result) {
							$('#resourceAdd').modal('hide');

							if (resourceData != null)
								bootbox.alert('更新资源失败！');
							else
								bootbox.alert('添加资源失败！');
						}
					});
				}
			});
		});
	};

	//删除资源
	var deleteRes = function(html) {
		var pageSize = $("#pageSize option:selected").text();
		var count = parseInt($("#showCount").html());
		var cpage = Math.ceil(count / pageSize);
		bootbox.confirm("确定删除吗？", function(result) {

			if (!result)
				return;

			var $html = $(html);
			var name = $html.find('#resName').html();
			var rurl = $html.find('#url').html();
			var rid = $html.find('#id').val();
			$.ajax({
				url: '/api/roleresource?',
				type: 'GET',
				data: {'_t': new Date().getTime()},
				success: function(data) {
					var check = false;
					for (var i = 0; i < data.length; i++) {
						if (data[i].resId == rid) {
							check = true;
						}
					}
					if (check) {
						bootbox.alert('资源已被授权给角色，不能删除！');
						return;
					}
					var delData = {
						id: rid,
						resName: name,
						resUrl: rurl
					};

					$.ajax({
						url: '/api/resource',
						type: 'DELETE',
						data: delData,
						success: function(result) {
							if(result == 'noPrivilege'){
								bootbox.alert('您没有权限,操作失败！');
								return;
							}
							if((count % pageSize) == 1) {
								cpage = cpage - 1;
							}
							dataPage(cpage);
						},
						error: function(result) {
							bootbox.alert("删除资源失败！");
						}
					});
				},
				error: function(data) {
					bootbox.alert('资源删除失败！');
					return;
				}
			});
		});
	};
});